<template>
  <Tabs :animated="false" v-model="activeTab" @on-click="handleTabClick">
    <TabPane label="基础信息" name="name1">
      <div></div>
    </TabPane>
    <TabPane label="服务信息" name="name2">
      <div style="display:flex;flex-direction:row;margin-bottom: 10px">
        <AddService></AddService>
<!--        <EditService :id="id"></EditService>-->
        <Input v-model="keyword" @on-search="searchPort" @on-clear="clearInput" search  placeholder="关键字搜索" clearable style="width: 200px;margin-right: 40px"/>
<!--        <Select  style="width: 200px;" v-model="EditStatus"  @change="editStatusData"  >-->
<!--          <Option v-for="item in EditStatusList" :value="item.value" :key="item.value">{{ item.label }}</Option>-->
<!--        </Select>-->
<!--        <Select  v-model="EditStatus"  placeholder="修改状态" >-->
<!--          <Option v-for="item in EditStatusList"  :value="item.value" :key="item.value">{{ item.label }}</Option>-->
<!--        </Select>-->
      </div>
      <div>
        <Table  @on-row-click="handleRowClick"	highlight-row border :columns="columns" :data="serviceData" size="small" ref="serviceTable"></Table>
      </div>
      <div>
        <Button style="margin-top: 10px" type="primary" @click="exportData(1)"><Icon type="ios-download-outline"></Icon>源数据导出</Button>
      </div>
      <div>
        <Page style="margin-top: 10px;text-align: center"  @on-change="handlePageChange" :current="currentPage" :total="total" show-total />
      </div>
    </TabPane>
    <TabPane label="主机信息" name="name3">
      <div style="display:flex;flex-direction:row">
        <AddHosts></AddHosts>
<!--        <Button disabled type="primary" style="margin-bottom: 10px">修改主机</Button>-->
      </div>
      <div style="font-weight: bold; font-size: 14px; padding-bottom:10px;  line-height: 18.5px; color: #333333;">测试环境</div>
      <div>
        <Table @on-filter-change="handleFilterChange"  highlight-row border :columns="hostcolumns" :data="hostData" size="small" ref="hostsTable"></Table>
      </div>
      <div style="font-weight: bold; font-size: 14px; padding-bottom:10px; padding-top:30px; line-height: 18.5px; color: #333333;">正式环境</div>
      <div>
        <Table></Table>
      </div>
    </TabPane>
    <TabPane label="漏洞信息" name="name4">
      <div style="display:flex;flex-direction:row;margin-bottom: 10px">
        <AddVulnerability></AddVulnerability>
      </div>
      <div>
        <Table highlight-row border :columns="vulnerabilitycolumns" :data="vulnerabilitydata" size="small" ></Table>
      </div>
    </TabPane>
  </Tabs>
</template>

<script>
import axios from "axios";
import AddHosts from "@/components/AddHosts.vue";
import AddService from "@/components/AddService.vue";
import EditService from "@/components/EditService.vue";
import AddVulnerability from "@/components/AddVulnerability.vue";

export default {
  components: {AddHosts,AddService,AddVulnerability},
  inject:['reload'],

  data() {
    return {
      vulnerabilitycolumns: [
        {title: '漏洞名称', key: 'name', align: 'center',
          render: (h, params) => {
            // 返回一个可点击的链接
            return h('a', {
              on: {
                click: () => {
                  this.$router.push(`/dashboard/projectlist/vulnerability?ability=${params.row.name}&company=${this.company}&tab=name1`);
                }
              }
            }, params.row.name);
          }
        },
        {title: '已修复', key: 'brepaired', align: 'center',
          render: (h, params) => {
            // 返回一个可点击的链接
            return h('a', {
              on: {
                click: () => {
                  this.$router.push(`/dashboard/projectlist/vulnerability?ability=${params.row.name}&company=${this.company}&tab=name2`);
                }
              }
            }, params.row.brepaired);
          }
        },
        {title: '未修复', key: 'unrepaired', align: 'center',
          render: (h, params) => {
            // 返回一个可点击的链接
            return h('a', {
              on: {
                click: () => {
                  this.$router.push(`/dashboard/projectlist/vulnerability?ability=${params.row.name}&company=${this.company}&tab=name3`);
                }
              }
            }, params.row.unrepaired); // 显示平台名称
          }
        },
        {title: '紧急程度', key: 'warn', align: 'center',
          render: (h, params) => {
            let color = 'default';
            if (params.row.warn === '紧急') {
              color = 'error';
            } else if (params.row.warn === '高') {
              color = 'warning';
            } else if (params.row.warn === '中') {
              color = 'success';
            }

            return h('tag', {
              props:{
                color:color
              },
              on: {
                click: () => {
                  this.$router.push('/dashboard/projectlist/vulnerability');
                }
              }
            }, params.row.warn); // 显示平台名称
          }
        },
        {title: '修复进度', key: 'reprogress', align: 'center'},
        {title: '修复完成时间', key: 'expectedtime', align: 'center'},

      ],
      hostcolumns: [
        {title: '主机名', key: 'hostname', align: 'center'},
        {title: 'IP', key: 'ip', align: 'center'},
        {title: '系统平台', key: 'system', align: 'center'},
        {title: 'K8s版本', key: 'version', align: 'center'},
        {title: '内核版本', key: 'kernel', align: 'center'},
        {title: 'docker版本', key: 'docker', align: 'center'},
        {title: '角色', key: 'role', align: 'center'}
      ],
      columns: [
        {title: '模块名称', key: 'module_name', fixed: 'left', width: 200, align: 'center'},
        {title: '研发人员', key: 'develop_name', align: 'center'},
        {title: '服务名称', key: 'server_name', align: 'center'},
        // {
        //   title: '代码修改', key: 'isedit', align: 'center', filters: [
        //     {
        //       label: '已修改',
        //       value: 1
        //     },
        //     {
        //       label: '未修改',
        //       value: 2
        //     }
        //   ],
        //   filterMultiple: false,
        //   filterMethod(value, row) {
        //     console.log(value)
        //     console.log(row)
        //     if (value === 1) {
        //       return row.isedit === '已修改';
        //     } else if (value === 2) {
        //       return row.isedit === '未修改';
        //     }
        //   }
        // },
        // {
        //   title: '代码部署', key: 'isdeploy', align: 'center', filters: [
        //     {
        //       label: '已部署',
        //       value: 1
        //     },
        //     {
        //       label: '未部署',
        //       value: 2
        //     }
        //   ],
        //   filterMultiple: false,
        //   filterMethod(value, row) {
        //     if (value === 1) {
        //       return row.isdeploy === '已部署';
        //     } else if (value === 2) {
        //       return row.isdeploy === '未部署';
        //     }
        //   }
        // },
        // {title: '分支名称', key: 'branch_name', align: 'center'},
        {
          title: '操作',
          key: 'more',
          align: 'center',
          render: (h, params) => {
            return h('div', {
              style: {
                display: 'flex',
                justifyContent: 'center'
              }
            }, [
              h('Button', {
                props: {
                  type: 'error'
                },
                style: {
                  marginRight: '10px'
                },
                on: {
                  click: () => this.deleteItem(params.row) // 这里传递当前行数据给删除方法
                }
              }, '删除'),
              h(EditService, {
                props: {
                  type: 'primary',
                  id:params.row.id,
                },
                on:{
                  'reload': this.getServiceData,
                }
              }, '编辑')
            ]);
          }
        }
      ],
      EditStatusList:[
        {value: '全部', label: "全部"},
        {value: '已修改',label: "已修改"},
        {value: '未修改',label: "未修改"},
        {value: '已部署',label: "已部署"},
        {value: '未部署',label: "未部署"}
      ],
      vulnerabilitydata:[],
      serviceData: [],
      hostData: [],
      NodeployCount:0,
      NoeditCount:0,
      activeTab: this.$route.query.tab, // 设置默认的选项卡
      company: this.$route.query.company, // 获取company参数
      id: null,
      total:0, //总数据条数
      currentPage: 1, // 当前页码
      keyword:'',
      EditStatus:'全部',  //设置默认选项为 全部
      DeployStatus:'',
    };
  },
  mounted() {
    this.getServiceData();
    this.getHostsData();
    this.getvulnerability();
  },
  methods: {
    //源数据导出
    exportData (type) {
      if (type === 1) {
        // 发送请求获取所有数据
        axios.get(`http://172.30.53.223:8888/export?company=${this.company}`,{
          responseType: 'blob' // 指定响应类型为 blob
        })
            .then(function(response) {
              // 创建一个临时链接
              const url = URL.createObjectURL(response.data);

              // 创建一个隐藏的 a 标签，设置下载链接
              const a = document.createElement('a');
              a.href = url;
              a.download = '服务列表.xlsx';

              // 点击下载链接
              a.click();

              // 释放链接资源
              URL.revokeObjectURL(url);
            })
            .catch(function(error) {
              console.error('导出失败:', error);
            });
      }
    },
    //获取服务列表
    getServiceData() {
      const selectedValue = this.EditStatusList[0].value;
      axios.get(`http://172.30.53.223:8888/api/projectlist/service?page=${this.currentPage}&company=${this.company}&keyword=${this.keyword}&status=${selectedValue}`)
          .then(response => {
            if (response.data.projectlist === null) {
              this.serviceData = [];
            } else {
              this.serviceData = response.data.projectlist.map(service => ({
                id: service.ID,
                module_name: service.ModuleName,
                develop_name: service.DevelopName,
                server_name: service.ServerName,
                isedit: service.Isedit,
                isdeploy: service.Isdeploy,
                branch_name: service.BranchName,
              }));
              this.total = response.data.matchCount;
            }
          });
    },
    //删除服务
    deleteItem() {
      this.$Modal.confirm({
        title: '提示',
        content: '<p>你确定要删除吗?</p>',
        onOk: () => {
          this.delete();
        },
        onCancel: () => {
          this.$Message.info('已取消');
        },
      });
    },
    async delete() {
      try {
        const response = await axios.post(`http://172.30.53.223:8888/api/projectlist/deleteservice?id=${this.id}&company=${this.company}`);
        if (response.status === 200) {
          this.$Message.success({ background: true, content: '删除成功' });
          this.reload()
        } else {
          throw new Error('Failed to delete.');
        }
      }catch (error) {
        console.error(error);
        this.$Message.error({ background: true, content: '删除失败' });
      }
    },
    //获取漏洞
    getvulnerability() {
      axios.get(`http://172.30.53.223:8888/api/vulnerability?company=${this.company}`)
          .then(response => {
            if (response.data.vulnerabilityList === null) {
              this.vulnerabilitydata = [];
            } else {
              this.vulnerabilitydata = response.data.vulnerabilityList.map(item => ({
                id: item.ID,
                name: item.Vname,
                brepaired: item.Brepaired,
                unrepaired: item.Unrepaired,
                warn: item.Warn,
                reprogress:item.Reprogress,
                expectedtime: item.Expectedtime,
              }));
            }
          });
    },
    //获取主机列表
    getHostsData() {
      axios.get(`http://172.30.53.223:8888/api/projectlist/hosts?company=${this.company}`)
          .then(response => {
            if (response.data.projectlist === null) {
              this.hostData = [];
            } else {
              this.hostData = response.data.projectlist.map(item => ({
                id: item.ID,
                hostname: item.HostName,
                ip: item.IP,
                system: item.System,
                version: item.K8s,
                kernel: item.Kernel,
                docker: item.Docker,
                role: item.Role,
              }));
            }
          });
    },
    handleFilterChange(filters) {
      console.log('过滤条件变化了:', filters);
      console.log(11111);
    },
    handlePageChange(currentPage){
      // 当页码变化时，更新currentPage并重新获取表格数据
      this.currentPage = currentPage;
      this.getServiceData();
    },
    handleRowClick(currentRow) {
      this.id = currentRow.id
    },
    background(type) {
      this.$Message[type]({
        background: true,
        content: type === 'success' ? '添加成功' : '添加失败'
      });
    },
    handleTabClick(tab) {
      this.activeTab = tab; // 点击选项卡时更新当前的选项卡
      this.$router.push(`/dashboard/projectlist/projectdetails?company=${this.company}&tab=${tab}`);
    },
    searchPort() {
      this.currentPage = 1
      this.getServiceData();
    },
    clearInput() {
      this.keyword = ''; // 清空关键字
      this.getServiceData(); // 重新获取服务数据
    },
  }
}
</script>
